<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" width="120" type="index" :index="indexMethod" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="success">分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="hEdit(scope.row)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="hDel(scope.row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件 -->
              <el-pagination
                :current-page="page"
                :page-sizes="[1, 2, 3, 5]"
                :page-size="pagesize"
                :total="total"
                layout="total,sizes,prev,pager,next"
                @size-change="hSizeChange"
                @current-change="hCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <!-- 新增弹框 -->
    <el-dialog
      :title="isEdit ? '编辑' : '添加'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      @close="hClose"
    >
      <el-form
        ref="roleForm"
        :model="roleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="showDialog = false">取消</el-button>
          <el-button
            size="small"
            type="primary"
            @click="hSubmit"
          >确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getRoles, deleteRole, addRole, updateRole } from '@/api/roles'
export default {
  data() {
    return {
      isEdit: false, // 状态为 编辑 | 添加
      showDialog: false, // 弹层是否显示隐藏
      list: [],
      total: 0, // 总条数
      page: 1, // 页码
      pagesize: 2, // 每页显示多少条
      // 表单
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', tirgger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', tirgger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    hClose() {
      // 重置表单
      this.roleForm = {
        name: '',
        description: ''
      }
      // 重置表单校验
      this.$refs.roleForm.resetFields()
    },
    async doEdit() {
      try {
        // 1.发送请求
        await updateRole(this.roleForm)
        // 2.提示
        this.$message.success('修改成功')
        // 3.重新加载数据
        this.loadRoles()
        // 4.关闭弹层
        this.showDialog = false
      } catch (err) {
        console.log(err)
        this.$message.error('修改失败')
      }
    },
    hEdit(data) {
      // 1.打开弹层
      this.showDialog = true
      // 2.将内容渲染在表单上
      this.roleForm = { ...data }
      // 3.设置状态为编辑
      this.isEdit = true
    },
    async doAdd() {
      try {
        // 1.发送请求
        await addRole(this.roleForm)
        this.total++
        this.page = Math.ceil(this.total / this.pagesize)
        // 2.提示
        this.$message.success('添加成功')
        // 3.重新加载数据
        this.loadRoles()
        // 4.关闭弹层
        this.showDialog = false
      } catch (err) {
        console.log(err)
        this.$message.error('添加失败')
      }
    },
    // 用户点击添加
    hAdd() {
      // 1.打开弹层
      this.showDialog = true
      // 2.设置状态为添加
      this.isEdit = false
    },
    // 确认按钮
    hSubmit() {
      // 表单校验
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    // 序号
    indexMethod(index) {
      return index + (this.page - 1) * this.pagesize + 1
    },
    // 更新页码
    hCurrentChange(val) {
      this.page = val
      this.loadRoles()
    },
    // 更新每页显示多少条
    hSizeChange(val) {
      this.pagesize = val
      // 每次更新页数,页码为1
      this.page = 1
      this.loadRoles()
    },
    async doDel(id) {
      try {
        // 1.发送请求
        await deleteRole(id)
        // 2.提示
        this.$message.success('删除成功')
        // 重新加载数据
        this.loadRoles()
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败')
      }
    },
    // 用户点击删除
    hDel(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 确定
          // 判断删除的那一页是最后一条并且页码大于1
          if (this.list.length === 1 && this.page > 1) {
            this.page--
          }
          this.doDel(id)
        })
        .catch(() => {
          // 取消
        })
    },
    // 加载数据
    async loadRoles() {
      const res = await getRoles({ page: this.page, pagesize: this.pagesize })
      this.list = res.data.rows
      this.total = res.data.total
    }
  }
}
</script>
